package com.wf.it.hpstatic;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
public class ResourceController {
    @Value("${my.resource.dir}")
    private String dir;
    @PostMapping(value="/upload")
    @ResponseBody
    public Map<String,Object> upload(String sondir, MultipartFile file, HttpServletResponse response) throws IOException {
        String uploaddir=dir+sondir;
        File fdir=new File(uploaddir);
        if(!fdir.exists())
            fdir.mkdirs();
        String ext=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newfilename= UUID.randomUUID().toString()+ext;
        file.transferTo(new File(uploaddir+"/"+newfilename));
        Map<String,Object> map=new HashMap<>();
        map.put("state",200);
        map.put("obj",newfilename);
        map.put("msg","ok");
        return map;
    }

    @PostMapping(value="/del")
    @ResponseBody
    public Map<String,Object> upload(String sondir, String filename, HttpServletResponse response) throws IOException {
        Map<String,Object> map=new HashMap<>();
        String filepath=dir+sondir+"/"+filename;
        File ff=new File(filepath);
        if(!ff.exists()){
            map.put("state",500);
            map.put("obj",null);
            map.put("msg","file is not exists");
            return map;
        }
        ff.delete();
        map.put("state",200);
        map.put("obj",null);
        map.put("msg","ok");
        return map;
    }
}
